package other.system.client.oa.submit;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.rkhd.platform.sdk.data.model.BidSeal__c;
import com.rkhd.platform.sdk.exception.ApiEntityServiceException;
import com.rkhd.platform.sdk.exception.ScriptBusinessException;
import com.rkhd.platform.sdk.log.Logger;
import com.rkhd.platform.sdk.log.LoggerFactory;
import com.rkhd.platform.sdk.model.QueryResult;
import com.rkhd.platform.sdk.service.XoqlService;
import com.rkhd.platform.sdk.task.FutureTask;
import org.apache.commons.lang.StringUtils;
import other.system.client.util.HCXObjectService;
import other.system.client.util.ResultBody;
import other.system.client.util.TfReturnMsgTools;

import java.util.List;
import java.util.Objects;

/**
 * @Description: 推送投标审批数据到OA（用于在生产环境上进行测试）
 * @Author: 黎炎松
 * @Date: 2024/7/9 17:36
 */
public class SubmitBid2 extends SubmitSuper {

    private static HCXObjectService hcxObjectService = new HCXObjectService();

    private static XoqlService xoqlService = XoqlService.instance();

    private static final String LOGGER_MSG = "推送投标审批数据到OA ==> ";

    private static final Logger logger = LoggerFactory.getLogger();

    public static void main(String[] args) {
        SubmitBid2 submitBid = new SubmitBid2();
        // 需切换测试环境进行测试，正式环境发送会导致他们的人员账号收到审批提醒
        submitBid.pushBidToOA(3453007871826511L);
    }

    /**
     * 推送投标盖章类数据到OA审批  bidSeal__c
     * @param
     * @return
     */
    public String pushBidToOA(Long bidId) {
        try {
            logger.info(LOGGER_MSG + "处理开始: " + bidId);

            // 获取投标类信息
            String sql = "select id,name,itemCoding__c,departmentTeam__c,stampedBy__c,stampsNumber__c," +
                    "stampingReason__c,sealType__c,YNKa__c,customerName__c.accountName accountName,oaApprovalId__c," +
                    "oaApprovalStatus__c,attachment__c,signatureNode__c.LoginName__c oaAccount,signatureNode__c.personalEmail oaEmail," +
                    "ownerId.LoginName__c ownerOaAccount,ownerId.personalEmail ownerOaEmail " +
                    " from bidSeal__c where id = " + bidId;
            QueryResult<JSONObject> query = xoqlService.query(sql, true);
            List<JSONObject> records = query.getRecords();
            if (records.size() <= 0) {
                logger.error(LOGGER_MSG + "获取投标数据异常");
                return TfReturnMsgTools.getFailResult("获取投标数据异常:" + query.getErrorMessage());
            }
            JSONObject bidSeal = records.get(0);
            String name = bidSeal.getString("name");
            String oaApprovalId = bidSeal.getString("oaApprovalId__c");
            String oaApprovalStatus = getOptionStr(bidSeal.getJSONArray("oaApprovalStatus__c"));
            // 如果是 作废 状态，则重新提交
            if (Objects.equals(oaApprovalStatus, "作废")) {
                oaApprovalId = "";
            }

            // 判断 【所属部门/团队】 是否为空，进行提示
            String departmentTeamVal = bidSeal.getString("departmentTeam__c");
            if (StringUtils.isBlank(departmentTeamVal)) {
                logger.error(LOGGER_MSG + "当前数据【所有人】部门下的'项目所属部门团队'为空，请联系管理员进行配置");
                return TfReturnMsgTools.getFailResult("当前数据【所有人】部门下的'项目所属部门团队'为空，请联系管理员进行配置");
            }

            // 拼接表单的数据
            JSONObject formObject = new JSONObject();
            formObject.put("fd_37b206a1075000", name); // 文件名称
            formObject.put("fd_389b41aaed4cae", bidSeal.getString("itemCoding__c")); // PMS项目编码
            formObject.put("fd_385c5756ba0d94", departmentTeamVal); // 所属部门、团队
            formObject.put("fd_37cecf1252aa7a", getOptionStr(bidSeal.getJSONArray("stampedBy__c"))); // 盖章主体
            formObject.put("fd_37b206c9607924", bidSeal.getString("stampsNumber__c")); // 盖章数量
            formObject.put("fd_37b206a8f5cdf6", bidSeal.getString("stampingReason__c")); // 盖章原因
            formObject.put("fd_3b5ce1800cdca4", getOptionStr(bidSeal.getJSONArray("sealType__c"))); // 印章类型
            formObject.put("fd_37fe192743a588", getOaAccount(bidSeal, 1)); // 加签节点
            formObject.put("fd_3cb12aab88898c", bidSeal.getString("YNKa__c")); // 是否KA
            formObject.put("fd_3d0ad353f737ec", bidSeal.getString("accountName")); // 客户名称（最终用户）
            logger.info(LOGGER_MSG + "formObject: " + formObject);

            // 获取所有人的OA账号 发送请求
            JSONObject ownerOaAccount = getOaAccount(bidSeal, 2);
            ResultBody resultBody = pushReqToOa("bid2", name, oaApprovalId, ownerOaAccount, formObject, null);
            logger.info(LOGGER_MSG + "resultBody: " + resultBody);
            if (!Objects.equals(resultBody.getCode(), "200")) {
                logger.error(LOGGER_MSG + "推送投标盖章类数据到OA异常: " + resultBody.getMessage());
                return TfReturnMsgTools.getFailResult("推送投标盖章类数据到OA异常:" + resultBody.getMessage());
            }

            // 返回的 id 进行保存
            String newOAId = resultBody.getResult().toString();
            BidSeal__c upBidSeal = new BidSeal__c();
            upBidSeal.setId(bidId);
            upBidSeal.setOaApprovalId__c(newOAId);
            upBidSeal.setOaApprovalStatus__c(1);
            upBidSeal.setLockStatus(2);
            Boolean update = hcxObjectService.update(upBidSeal);
            logger.info(LOGGER_MSG + "update: " + update);

            // 撤回后重新提交需要修改OA的数据状态为 已提交
            if (StringUtils.isNotBlank(oaApprovalId) && (Objects.equals(oaApprovalStatus, "撤回") || Objects.equals(oaApprovalStatus, "驳回"))) {
                resubmitApprovalData(oaApprovalId, ownerOaAccount);
            }

            // 单独的方法更新附件
            JSONArray fileList = bidSeal.getJSONArray("attachment__c"); // 附件
            UploadOAFile.syncUoloadFile(newOAId, fileKeyMap.get("bid2"), fileList);

            logger.info(LOGGER_MSG + "提交成功");
            return TfReturnMsgTools.getSuccessResult("提交成功");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(LOGGER_MSG + "处理异常: " + e.getMessage());
            return TfReturnMsgTools.getFailResult("推送异常:" + e.getMessage());
        }
    }

}
